#!/bin/sh
#desc:Verbalize
#type:redundant
#package:odspeech
#author:danix

# Copyright(c) 2011 OpenDomo Services SL. Licensed under GPL v3 or later

LEVEL="$1"
MODULE="$2"
TEXT="$3"

LOGEVENT="/bin/logevent"
MODULE="odspeech" #Overwrite, in case the name is wrong.
ERROR="error"
WARN="warning"

if [ $# -lt 3 ]; then
    ${LOGEVENT} ${WARN} ${MODULE} "Three arguments needed."
    exit 1
fi

LANG=$(cat /etc/opendomo/i18n/lang)

CFG="/etc/opendomo/speech.conf"
KEYFILE="/var/opendomo/i18n/key"
LANGFILE="/var/opendomo/i18n/$LANG"
SETCONF="/usr/local/opendomo/services/config/speechSettings.sh"
I18N="/usr/local/bin/i18n.sh"

if test -f "$CFG" ; then
	# The config file exists, so we load it.
	. $CFG
else
    ${LOGEVENT} ${WARN} ${MODULE} "[${CFG}] does not exist. Creating..."

	if test -x /usr/bin/espeak; then
		program="espeak"
		gender="m"  #Config. Can be f or m (male or female)
		variant="1" #Config. Can be number or croak or whisper, or a personalone.
		speed="140" #Config.
		amplitude="100" #Config.
		pitch="50"  #Config.
	else
		if test -x /usr/bin/flite; then
			program="flite"
		fi
	fi
	echo "program='$program'">$CFG
	echo "gender='$gender'" >> $CFG
	echo "variant='$variant'" >> $CFG
	echo "amplitude='$amplitude'" >> $CFG
	echo "pitch='$pitch'" >> $CFG
	echo "speed='$speed'" >> $CFG

    if [ $? -eq 0 ]; then
        #Do something?
        echo > /dev/null
    else
        ${LOGEVENT} ${ERROR} ${MODULE} "[${CFG}] could not be created."
        exit 1
    fi

fi

if [ ! -f ${LANGFILE} ]; then
    ${LOGEVENT} ${ERROR} ${MODULE} "[${LANGFILE}] does not exist."
    exit 1
fi

TRANS_TEXT=$(${I18N} "${TEXT}")

SPEECH_FILE=/tmp/speech$(date +%Y%m%d%H%M%S)_tmp.wav

# Load actual configuration
if test -f $CFG; then
	. $CFG
else
	${LOGEVENT} ${ERROR} ${MODULE} "[${CFG}] does not exist. Some previous step failed."
	exit 1
fi

# Prepare options for TTSs
case $program in 
	"espeak")
		# Run TTS saving to file
		OPT="-v$LANG+$gender$variant -s $speed -a $amplitude -p $pitch "
		/usr/bin/espeak "$TRANS_TEXT" $OPT -w $SPEECH_FILE 2>/dev/null
	;;
	"flite")
		echo "$TRANS_TEXT" | /usr/bin/flite -o $SPEECH_FILE
	;;
	*)
		${LOGEVENT} ${ERROR} ${MODULE} "INVALID synthetizer"
	;;
esac


# Play and remove file
if test -f $SPEECH_FILE; then
	/usr/bin/aplay -q $SPEECH_FILE &
#	rm $SPEECH_FILE
fi
